/**
 * Created by admin on 2016/8/9.
 */
var assert = require('../assert');
// 提交一个退款申请
exports.postOrderReturn = function (req, res) {
    console.log(req.body);
    // 获取请求参数
    var userId = req.body.userId;
    var orderProductId = req.body.orderProductId;
    var needReturn = req.body.needReturn;
    var content = req.body.content;
    var imgUrls = req.body.images;
    if(imgUrls){
        imgUrls = JSON.parse(imgUrls);
    }
    var orderId = req.body.orderId;


    if (needReturn == 'false'){
        needReturn = false;
    }else if (needReturn == 'true'){
        needReturn = true;
    }else {
        res.send(assert.response_sms(101, 'needReturn参数错误'));
        return
    }
    //判断参数为空的情况
    if (!(userId && orderProductId && orderId && content)){
        res.send(assert.response_sms(102, 'userId，orderProductId，needReturn，orderId，content参数不能为空'));
        return
    }
    // 创建user对象
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;

    getOrder(orderId).then(function (result) {
        var order = result;
        // 实例化orderReturnProgress对象
        var OrderReturnProgress = Parse.Object.extend('OPOrderReturnProgress');
        var orderReturnProgress = new OrderReturnProgress();
        orderReturnProgress.set('status', true);
        orderReturnProgress.set('content', '您的退款申请已提交,请等待工作人员审核');
        // 保存orderProduct对象
        var OrderReturn = Parse.Object.extend('OPOrderReturn');
        var orderReturn = new OrderReturn();
        // 判断是否要存储退货原因
        if (needReturn){
            var reason = req.body.reason;
            orderReturn.set('reason', reason);
        }

        // 商品总数量
        var totalCount = 0;
        // 退单
        var returnOrderProduct = null;
        // 计算商品总数量，查找对应的orderProduct
        for (var i=0; i<order.get('orderProducts').length; i++){

            var orderProduct = order.get('orderProducts')[i];
            if (orderProduct.id == orderProductId){
                returnOrderProduct = orderProduct;
            }
            totalCount += orderProduct.get('count');
        }
        // 计算退款金额

        var returnPrice = returnOrderProduct.get('count') * returnOrderProduct.get('price') - (order.get('privilegePrice')/totalCount).toFixed(1);
        orderReturn.set('user', user);
        orderReturn.set('order', order);
        orderReturn.set('status', 0);
        orderReturn.set('content', content);
        if (imgUrls){
            orderReturn.set('imgUrls', imgUrls);
        }
        orderReturn.set('needReturn', needReturn);
        orderReturn.set('returnPrice', returnPrice);
        orderReturn.set('orderProduct', returnOrderProduct);
        orderReturn.set('returnProgress', [orderReturnProgress]);
        orderReturn.save().then(function (results) {
            // 给orderProduct绑定一个orderReturn
            returnOrderProduct.set('orderReturn', results);
            returnOrderProduct.save().then(function (result) {
                console.log('orderProduct绑定orderReturn成功');
            }, function (error) {
                console.log('orderProduct绑定orderReturn失败', error);
            });

            res.send(assert.response_sms(200, '退款申请成功' , {'objectId': results.id}));
        }, function (error) {
            res.send(assert.response_sms(201, '退款申请失败' + error.message));
        });
    }, function (error) {
        console.log(error.message);
    });
};
// 获取退货订单列表
exports.getOrderReturns = function (req, res) {
    var userId = req.query.userId;
    if (!userId){
        res.send(assert.response_sms(400, 'userId为空'));
        return
    }
    // 实例化user对象
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    // 实例化查询对象
    var query = new Parse.Query('OPOrderReturn');
    query.equalTo('user', user);
    query.include('user');
    query.include('returnProgress', 'orderProduct.product');
    query.find().then(function (results) {
        // 格式化返回的字段
        var response_content = [];
        for (var i=0; i<results.length; i++){
            var temp = {};
            temp['status'] = results[i].get('status');
            temp['title'] = results[i].get('orderProduct').get('product').get('title');
            temp['images'] = results[i].get('orderProduct').get('product').get('images')[0];
            temp['count'] = results[i].get('orderProduct').get('count');
            temp['price'] = results[i].get('orderProduct').get('price');
            try {
                // temp['update_at'] = typeof (results[i].get('updatedAt'));
                var format_time = results[i].get('updatedAt');
                temp['update_at'] = format_time.getFullYear() + '-' + format_time.getMonth() + '-' + format_time.getDate() + ' ' + format_time.getHours() + ':' + format_time.getMinutes();
            }catch (error){
                console.log(error);
                temp['update_at'] = results[i].get('updatedAt');
            }
            temp['objectId'] = results[i].id;
            temp['needReturn'] = results[i].get('needReturn');
            response_content.push(temp);
        }
        res.send(assert.response_sms(200, '获取退单列表成功', response_content));
    }, function (error) {
        res.send(assert.response_sms(400, '获取退单表单失败' + error.message))
    });
};
// 获取单个退货订单
exports.getOrderReturn = function (req, res) {
    var orderReturnId = req.params.orderReturnId;
    if (!orderReturnId){
        res.send(assert.response_sms(400, '参数错误'));
        return
    }
    // 实例化查询对象
    var query = new Parse.Query('OPOrderReturn');
    query.include('returnProgress', 'orderProduct.product');
    query.get(orderReturnId).then(function (result) {
        // 格式化orderReturn
        var temp_orderReturn = assert.obj2dic(result,['status', 'returnPrice', 'needReturn']);
        temp_orderReturn['returnProgress'] = [];
        // 格式化每个returnProgress
        for (var i=0; i<result.get('returnProgress').length; i++){
            var temp_returnProgress = assert.obj2dic(result.get('returnProgress')[i],['status', 'content']);
            temp_returnProgress['createdAt'] = result.get('returnProgress')[i]['createdAt'].Format('yyyy-MM-dd hh:mm');
            temp_orderReturn['returnProgress'].unshift(temp_returnProgress);
        }
        // 格式化orderReturn里的orderProduct
        temp_orderReturn['orderProduct'] = assert.obj2dic(result.get('orderProduct'),['price', 'count']);
        temp_orderReturn['orderProduct']['title'] = result.get('orderProduct').get('product').get('title');
        temp_orderReturn['orderProduct']['image'] = result.get('orderProduct').get('product').get('images')[0];
        res.send(assert.response_sms(200, '获取指定退单成功', temp_orderReturn));
    }, function (error) {
        res.send(assert.response_sms(400, '获取指定退单失败' + error.message))
    });
};
// 编辑退单（取消退单）
exports.editOrderReturn = function (req, res) {
    var orderReturnId = req.params.orderReturnId;
    var status = parseInt(req.body.status);
    if (!(orderReturnId && status)){
        res.send(assert.response_sms(400, '参数错误'));
        return
    }
    var query = new Parse.Query('OPOrderReturn');
    // 查询对应的订单
    query.get(orderReturnId).then(function (orderReturn) {
        if (status== '4'){
            var orderProduct = orderReturn.get('orderProduct');
            orderProduct.unset('orderReturn');
            orderProduct.save().then(function (result) {
                orderReturn.destroy().then(function (result) {
                    res.send(assert.response_sms(200, '取消申请成功'));
                }, function (error) {
                    res.send(assert.response_sms(400, '取消申请失败'));
                });
            }, function (error) {
                res.send(assert.response_sms(401, 'orderProduct解除绑定orderReturn失败'));
            })
        }else {
            // 获取Progress对象
            var progresses = orderReturn.get('returnProgress');
            // 建立先得orderProgress对象
            var OrderReturnProgress = Parse.Object.extend('OPOrderReturnProgress');
            var orderReturnProgress = new OrderReturnProgress();
            orderReturnProgress.set('status', true);
            orderReturnProgress.set('content', '您已经取消申请退单');
            progresses.push(orderReturnProgress);
            orderReturn.set('returnProgress', progresses);
            orderReturn.set('status', status);
            return orderReturn.save();
        }
    }, function (error) {
        res.send(assert.response_sms(400, '取消申请失败, 未获取到相应的退款申请' + error.message));
    }).then(function (result) {
        res.send(assert.response_sms(200, '取消申请成功'));
    }, function (error) {
        res.send(assert.response_sms(400, '取消申请失败'));
    });
};
// 删除退单
exports.deleteOrderReturn = function (req, res) {
    var orderReturnId = req.params.orderReturnId;
    if (!orderReturnId){
        res.send(assert.response_sms(400, '参数错误'));
        return
    }
    var query = new Parse.Query('OPOrderProduct');
    query.get(orderReturnId).then(function (orderReturn) {
        return orderReturn.destroy();
    }, function (error) {
        res.send(assert.response_sms(400, '删除失败, 未获取到相应的退款申请' + error.message));
    }).then(function (result) {
        res.send(assert.response_sms(200, '删除成功'));
    }, function (error) {
        res.send(assert.response_sms(400, '删除失败' + error.message));
    });

};
// 给后台用来设置退款退货进度
exports.setOrderReturnProgress = function (req, res) {
    var orderReturnId = req.params.orderReturnId;
    var status = parseInt(req.body.status);
    if (!(orderReturnId && status)){
        res.send(assert.response_sms(400, '参数错误'));
        return
    }
    var query = new Parse.Query('OPOrderReturn');
    query.get(orderReturnId).then(function (orderReturn) {
        var progresses = orderReturn.get('returnProgress');
        var OrderReturnProgress = Parse.Object.extend('OPOrderReturnProgress');
        var orderReturnProgress = new OrderReturnProgress();
        orderReturnProgress.set('status', true);
        var content = '';
        switch (status){
            case 1:
                content = '您的退货申请已通过审核，请将商品寄回';
                break;
            case 2:
                content = '已收到您的退货商品，会尽快办理退款';
                break;
            case 3:
                content = '退单完成';
                break;
            case 5:
                content = '审核未通过，不同意退单';
                break;
        }
        orderReturnProgress.set('content', content);
        progresses.push(orderReturnProgress);
        return orderReturn.save();
    }, function (error) {
        res.send(assert.response_sms(400, '取消申请失败, 未获取到相应的退款申请' + error.message));
    }).then(function (result) {
        res.send(assert.response_sms(200, '取消申请成功'));
    }, function (error) {
        res.send(assert.response_sms(400, '取消申请失败' + error.message));
    });
};

// 获取orderProduct对象
function getOrderProduct(orderProductId) {
    return new Promise(function (resolve, reject) {
        var query = new Parse.Query('OPOrderProduct');
        query.get(orderProductId).then(function (orderProduct) {
            resolve(orderProduct)
        }, function (error) {
            reject(error)
        });
    })
}

function getOrder(orderId) {
    return new Promise(function (resolve, reject) {
        var query = new Parse.Query('OPOrder');
        query.include('orderProducts');
        query.get(orderId).then(function (order) {
            resolve(order)
        }, function (error) {
            reject(error)
        });
    })
}